package ch02.shiLi;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

public class showPhoneInfo2 {
    public static void main(String[] args) throws DocumentException, IOException {
        //读取XML文件,，获取Document对象
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(new File("src/ch02/shiLi/收藏信息.xml"));
        System.out.println(doc);

        //循环输出信息
        Element rootElement = doc.getRootElement();
        Element brand =  rootElement.elements("Brand").get(0);
        Element item = brand.element("Item");
        Element title = item.element("title");
        System.out.println(title.getText());
        for (Iterator itBrand=rootElement.elementIterator();itBrand.hasNext();){
            Element brands = (Element) itBrand.next();
            System.out.print(brands.attributeValue("name"));
            for (Iterator itType=brands.elementIterator();itType.hasNext();){
                Element type = (Element) itType.next();
                System.out.println(type.attributeValue("name"));
            }
        }
        //添加
        Element brand1 = DocumentHelper.createElement("Brand");
        brand1.addAttribute("name","OPPO");
        Element type = DocumentHelper.createElement("Type");
        type.addAttribute("name","A3");
        brand1.add(type);
        rootElement.add(brand1);
        Element brand3 = rootElement.addElement("Brand");
        brand3.addAttribute("name","VIVO");

        //修改
        for (Iterator itBrand=rootElement.elementIterator();itBrand.hasNext();){
            Element brands = (Element) itBrand.next();
            System.out.println(brands.attributeValue("name"));
            if (brands.attributeValue("name").equals("华为")){
                Attribute name = brands.attribute("name");
                name.setText("荣耀");
            }
        }

        //删除
        for (Iterator itBrand=rootElement.elementIterator();itBrand.hasNext();){
            Element brands = (Element) itBrand.next();
            System.out.println(brands.attributeValue("name"));
            if (brands.attributeValue("name").equals("VIVO")){
                rootElement.remove(brands);
            }
        }
        OutputFormat compactFormat = OutputFormat.createCompactFormat();
        compactFormat.setEncoding("UTF-8");
        XMLWriter xmlWriter = new XMLWriter(new FileWriter("src/ch02/shiLi/收藏信息.xml"));
        xmlWriter.write(doc);
        xmlWriter.close();
    }

}
